package cn.mugutu.finance.controller;

import cn.mugutu.finance.domain.system.User;
import cn.mugutu.finance.dto.BaseResult;
import cn.mugutu.finance.exception.BusinessException;
import cn.mugutu.finance.query.BaseQuery;
import cn.mugutu.finance.utils.ConstantConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 公共的Controller
 */
public class BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseController.class);

    /** 当前线程请求request对象 */
    @Autowired
    protected HttpServletRequest request;
    /** 当前线程在服务器的session对象 */
    @Autowired
    protected HttpSession session;

    /**
     * 获取当前登陆用户
     * @return
     */
    public User getLoginUser() {
        HttpSession session = request.getSession();
        return (User) session.getAttribute(ConstantConfig.USER_IN_SESSION);
    }

    /**
     * 首页路径
     * @return
     */
    protected String getIndexPage() {
        return getClass().getSimpleName().replace("Controller", "").toLowerCase();
    }

    /**
     * 修改或编辑页路径
     * @return
     */
    protected String getEditPage() {
        return getIndexPage() + "/edit";
    }

    /**
     * 查看页路径
     * @return
     */
    protected String getListPage() {
        return getIndexPage() + "/list";
    }

    /**
     * 无权访问的页面
     * @return
     */
    protected String noPrivilege() {
        return "home/noprivilege";
    }

    /**
     * 前台框架用easyui的时候将前台分页参数设置给查询对象
     * @param baseQuery
     * @param page
     * @param rows
     * @return
     */
    public BaseQuery setEasyUIParamsInQuery(BaseQuery baseQuery, int page, int rows) {
        baseQuery.setCurrentPage(page);
        baseQuery.setPageSize(rows);
        return baseQuery;
    }

    /** 基于@ExceptionHandler异常处理 (返回JSON)*/
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseResult exp(HttpServletRequest request, Exception ex) {
        ex.printStackTrace();
        if (ex instanceof BusinessException) {
            BusinessException bex = (BusinessException) ex;
            return new BaseResult(false, ex.getMessage(), bex.getCode());
        }
        return new BaseResult(false, ex.getMessage());
    }

    /** 返回成功 */
    protected BaseResult success() {
        return new BaseResult(true, "操作成功");
    }

    /** 返回成功 */
    protected BaseResult success(String msg) {
        return new BaseResult(true, msg);
    }

    /** 返回失败 */
    protected BaseResult error() {
        return new BaseResult(false, "操作失败");
    }

}
